package com.cloudfast.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final String Authorization = "Authorization";

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {
                if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
                    response.setHeader(Authorization, request.getHeader(Authorization));
                    response.setHeader("Expires", "3600");
                    response.setHeader("Access-Control-Max-Age", "3600");
                    response.setStatus(HttpStatus.OK.value());
                    response.getWriter().write("OPTIONS returns OK-->" + request.getHeader(Authorization));
                    response.setHeader("Access-Control-Allow-Headers",
                            "Content-Type, x-requested-with, X-Custom-Header, Authorization,token");
                    return false;
                }
                return true;
            }

        });
        interceptorRegistration.addPathPatterns("/**");
    }

}
